package com.gin.no_gay_alliance.adpter.topic;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gin.common.utils.TimeAgo;
import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.callback.AbstractRedirectCallback;
import com.gin.nga.response.ReplyLocation;
import com.gin.nga.utils.AnonymousUtils;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.TopicReadActivity;
import com.gin.no_gay_alliance.adpter.base.BaseBindingRecyclerViewAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.customview.ContentWebViewRender;
import com.gin.no_gay_alliance.databinding.ItemTopicBinding;
import com.gin.no_gay_alliance.listener.ListenerUtils;
import com.gin.no_gay_alliance.utils.ReplyStatusUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.TopicItem;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import okhttp3.Call;

/**
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/24 10:13
 **/
public class TopicItemAdapter extends BaseBindingRecyclerViewAdapter<ItemTopicBinding, TopicItem> implements View.OnClickListener, View.OnLongClickListener, CompoundButton.OnCheckedChangeListener {
    public static final String TAG = TopicItemAdapter.class.getSimpleName();
    ContentWebViewRender contentWebViewRender;
    boolean showCheckBox = false;

    public TopicItemAdapter(Context context) {
        this(context, new ArrayList<>());
    }

    public TopicItemAdapter(@NonNull Context context, @NonNull List<TopicItem> data) {
        super(context, data);
        contentWebViewRender = new ContentWebViewRender(this.context, handler);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        TopicItem tag = (TopicItem) buttonView.getTag();
        tag.checked = isChecked;
    }

    @Override
    protected void onBindViewHolder(ViewHolder<ItemTopicBinding> holder, ItemTopicBinding b, int position, TopicItem item) {
        // 绑定item到根布局
        b.layoutParent.setTag(item);
        // 复选框
        ViewUtils.setGone(!showCheckBox, b.cb);
        b.cb.setTag(item);
        b.cb.setChecked(item.checked);
        b.cb.setOnCheckedChangeListener(this);


        // 主题状态
        ReplyStatusUtils.configTopic(item.mirror, item.replyOnce, item.status, b.layoutTopicStatus, context);
        // 标记入口类型
        TopicItemRecentAdapter.markEntranceType(item, b.layoutTopicStatus, context);
        // 主题标题
        b.tvTitle.setText(item.title);
        configTitle(item, b.tvTitle);
        // 发布时间
        b.tvPostTime.setText(TimeAgo.ago(item.postDateTime));
        // 设置点击事件
        b.layoutParent.setOnClickListener(this);
        b.layoutParent.setOnLongClickListener(this);

        // 作者名
        b.tvAuthorName.setText(item.authorName);
        // 匿名标记
        b.tvAnonymous.setVisibility(AnonymousUtils.isAnonymous(item.authorId) ? View.VISIBLE : View.GONE);
        // 最后回复
        b.tvLastPosterName.setText(item.lastPosterName);
        // 回复数
        b.tvReplyCount.setText(String.format(Locale.CHINA, "(%d)", item.replyCount));
        // 最后回复人
        b.tvLastPost.setText(TimeAgo.ago(item.lastPost));
        // 版面名称
        if (!ObjectUtils.isEmpty(item.parentForumName)) {
            b.tvForumNameParent.setVisibility(View.VISIBLE);
            b.tvForumNameParent.setText(item.parentForumName);
        } else {
            b.tvForumNameParent.setVisibility(View.GONE);
        }
        // 主题内回复
        if (item.replyId != null) {
            // 渲染正文
            contentWebViewRender.render(position, b.layoutContent, holder, item.replyNodes);
            contentWebViewRender.setBlockNetworkImage(false);
            b.tvReplyTime.setVisibility(View.VISIBLE);
            b.tvReplyTime.setText(String.format(Locale.CHINA, "主题内回复: %s", item.replyTimestamp));
        } else {
            b.tvReplyTime.setVisibility(View.GONE);
        }
    }

    @NonNull
    @Override
    protected ItemTopicBinding buildBinding(LayoutInflater inflater) {
        return ItemTopicBinding.inflate(inflater);
    }

    @Override
    public void onClick(View v) {
        TopicItem tag = (TopicItem) v.getTag();
        if (v.getId() == R.id.layout_parent) {
            if (tag.replyId != null) {
                //跳转到回复
                MyApplication.getClient().toReply(tag.replyId, new AbstractRedirectCallback() {
                    @Override
                    protected void onRedirect(String location) {
                        TopicReadActivity.startActivity(context, new ReplyLocation(location));
                    }

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                });

            } else {
                // 打开主题
                ListenerUtils.onClickTopicItem(tag, context);
            }
        }
    }

    @Override
    public boolean onLongClick(View v) {
        //长按以最大页数打开
        if (v.getId() == R.id.layout_parent) {
            ListenerUtils.onLongClickTopicItem((TopicItem) v.getTag(), context);
            return true;
        }
        return false;
    }

    /**
     * 配置标题字体
     *
     * @param topicItem 主题项
     * @param tv        标题TextView
     */
    private void configTitle(TopicItem topicItem, TextView tv) {
        // 颜色
        if (topicItem.color == 0) {
            TypedValue typedValue = new TypedValue();
            context.getTheme().resolveAttribute(R.attr.textColor, typedValue, true);
            tv.setTextColor(typedValue.data);
        } else {
            tv.setTextColor(topicItem.color);
        }


        // 标题字体：加粗、删除、斜线
        tv.setTypeface(null);
        tv.setPaintFlags(tv.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
        // 加粗
        if (topicItem.bold) {
            tv.setTypeface(tv.getTypeface(), Typeface.BOLD);
        }
        // 斜体
        if (topicItem.italic) {
            tv.setTypeface(tv.getTypeface(), Typeface.ITALIC);
        }
        // 删除线
        if (topicItem.lineThrough) {
            tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        }
    }

    /**
     * 返回被选中的主题
     *
     * @return 被选中的主题
     */
    public List<TopicItem> getCheckedItem() {
        return data.stream().filter(i -> i.checked).collect(Collectors.toList());
    }

    /**
     * 设置本页所有主题的选中状态
     *
     * @param isChecked 是否选中
     */
    @SuppressLint("NotifyDataSetChanged")
    public void setAllChecked(boolean isChecked) {
        data.forEach(i -> i.checked = isChecked);
        notifyDataSetChanged();
    }

    public void setShowCheckBox(boolean showCheckBox) {
        this.showCheckBox = showCheckBox;
    }
}
